<?php

namespace app\controllers;

use yii\data\Pagination;
use yii\db\Query;
use yii\web\Controller;


class ArticleController extends AdminBaseController {


     public function actionIndex(){
         if ($this->post()){
             $title=\Yii::$app->request->post()['title'];
             $query=(new Query())->select('*')->from('yii_article')->where(['like','title',$title]);
         }else{
             $query=(new Query())->select('*')->from('yii_article');
         }
         $pages=new Pagination(['totalCount' =>$query->count()]);
         $pages->defaultPageSize = 10;//每页10条
         $list=$query->offset($pages->offset)->limit($pages->limit)->all();
         foreach ($list as $k=>$v){
             $list[$k]['cover']=$this->GetImg($v['cover']);
         }
         return $this->render('index',['list'=>$list,'pages'=>$pages]);

       }


       //添加
       public function actionAdd(){
         if ($this->post()){
             $data=\Yii::$app->request->post();
             unset($data['imageFile']);
             $data['create_time']=time();
             $data['update_time']=time();
             $res=\Yii::$app->db->createCommand()->insert('yii_article',$data)->execute();
             if ($res){
                 return json_encode(['code'=>1,'msg'=>'添加成功']);
             }else{
                 return json_encode(['code'=>0,'msg'=>'添加失败']);
             }
         }

           return $this->render('add');
       }

    //编辑
    public function actionEdit(){
        if ($this->post()){
            $data=\Yii::$app->request->post();
            unset($data['imageFile']);
            $data['update_time']=time();
            $res=\Yii::$app->db->createCommand()->update('yii_article',$data,array('id'=>$data['id']))->execute();
            if ($res){
                return json_encode(['code'=>1,'msg'=>'更新成功']);
            }else{
                return json_encode(['code'=>0,'msg'=>'更新失败']);
            }
        }
        $id=$this->GetId();
        $list=(new Query())->select('*')->from('yii_article')->where(array('id'=>$id))->one();
        $list['img']=$this->GetImg($list['cover']);
        return $this->render('edit',['list'=>$list]);
    }

    //删除
    public function actionDel(){
        $id=$this->PostId();
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $info=(new Query())->select('cover')->from('yii_article')->where(array('id'=>$id))->one();
            $this->DelFile($info['cover']);
            $this->DelPicture($info['cover']);
            \Yii::$app->db->createCommand()->delete('yii_article',array('id'=>$id))->execute();
            $transaction->commit();
            return json_encode(['code'=>1,'msg'=>'删除成功']);
        } catch (\Exception $e) {
            $transaction->rollBack();
            return json_encode(['code'=>0,'msg'=>'删除失败']);
        }
    }


}
